/*
 *   项目名称：train12306
 *   文件名称：com.xiaolon.train12306.common.interceptor.MemberInterceptor
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/26
 *
 */
package com.xiaolon.train12306.common.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xiaolon.train12306.common.context.LoginMemberContext;
import com.xiaolon.train12306.common.resp.MemberLoginResp;
import com.xiaolon.train12306.common.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 类描述： MemberInterceptor
 * 拦截器：Spring框架特有，用于登录校验，权限校验，请求日志打印
 **/
@Component
public class MemberInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取header的token参数
        String token = request.getHeader("token");
        if(StrUtil.isNotBlank(token)){
            LOG.info("获取会员登录token: {}", token);
            JSONObject loginMember = JwtUtil.getJSONObject(token);
            MemberLoginResp member = JSONUtil.toBean(loginMember, MemberLoginResp.class);
            LoginMemberContext.setMember(member);
        }
        return true;
    }
}